<?php
class updateGroundStatusTask extends sfBaseTask
{
  public function configure()
  {
    $this->namespace = 'backend';
    $this->name      = 'update-ground-status';
	$this->addOptions(array(
            new sfCommandOption('env', null, sfCommandOption::PARAMETER_REQUIRED, 'The environment', 'dev'),
            new sfCommandOption('connection', null, sfCommandOption::PARAMETER_REQUIRED, 'The connection name', 'doctrine'),
            new sfCommandOption('exp', null, sfCommandOption::PARAMETER_OPTIONAL, 'The new expiration date', ''),
            ));
  }
 
  public function execute($arguments = array(), $options = array())
  {
    // initialize database connection  
    $databaseManager = new sfDatabaseManager($this->configuration);
    $connection = $databaseManager->getDatabase($options['connection'])->getConnection();

	date_default_timezone_set('Asia/Bangkok');
	$today = date('Y-d-m', time());
	$q = Doctrine_Query::create()
		->from('DtGroundOrder go')
		->addWhere('go.status = ?', DtGroundOrder::STATUS_INIT)
		->addWhere('go.reserved_date <= ?', $today);
	$orders = $q->execute();
	foreach ($orders as $order) {
		echo "Parsering order: ".$order->order_code." with reserved date: ".$order->reserved_date." and schedule: ".$order->schedule."and status: ".$order->status."\n";
		if ($this->is_expired($order)) {
			echo "Order ".$order_code." will be changed to status expired\n";
			$order->status = DtGroundOrder::STATUS_EXPIRE;
			$order->save();
			DtReportPerDay::createOrUpdateDailyReport($order, true, false);
		}
	}
  }


  private function is_expired($order)
  {
	$schedule = substr($order->schedule,0, 5);
	$start_time = strtotime($order->reserved_date.' '.$schedule, '-2 hours');
	return ($start_time <= time() && $order->created_at < $start_time);
  }
}
?>